﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Orion.Models;
using Orion.MyLib;


namespace Orion.Controllers
{
    [Authorize(Roles = "Admin, Staff")]
	[HandleError]
    public class WorkNewsArticleController : Controller
    {
        public INewsArticleRepository m_rep = null;
        private IUserManager m_userMgr = null;
        HomeIndexViewModel m_NewsArticle = new HomeIndexViewModel();
        private int displayNewsArticles = 10;

        /*Unit test*/
        public WorkNewsArticleController()
        {
            m_rep = new NewsArticleRepositry();
            m_userMgr = new UserManager();
        }

        /*Unit test*/
        public WorkNewsArticleController(INewsArticleRepository rep, IUserManager usrMgr)
        {
            m_rep = rep;
            m_userMgr = usrMgr;
        }


        [HttpGet]
        public ActionResult EditNewsArticle( int? id )
        {
            //validation
            if ( ! id.HasValue )
            {
                return View ( "NotFound" );
            }
            var model = m_rep.GetNewsArticleById( id.Value );

            return View( model );
        }

        [ValidateInput(false)]
        [HttpPost]
		public ActionResult EditNewsArticle(FormCollection form, HttpPostedFileBase file)
        {
        	try
        	{
				//validation
				if( ! ModelState.IsValid )
				{
					return View( form );
				}

				var na = new NewsArticle();
				UpdateModel( na );

				//ID is returned as string, for some reason need to change it back to int for use.
				int temp;
				if ( ! int.TryParse( form["ID"], out temp ) )
				{
					throw new Exception("ID af atburð tapaðist við tilraun til þess að breyta honum");
				}
				na.ID = temp;

				//check if file has been submited
				if (file != null && file.ContentLength > 0)
				{
					//file saved to hard drive and relative path from web aplication saved
					var fileEnding = file.FileName.Split('.');
					var folder = Path.Combine(Server.MapPath("~/Content/ArticleMyndir"));
					var path = Path.Combine(Server.MapPath("~/Content/ArticleMyndir"), na.Title.Trim() + "." + fileEnding[1]);

					//validate folder exist
					if (!Directory.Exists(folder))
					{
						Directory.CreateDirectory(folder);
					}

					file.SaveAs(path);
					na.Picture = string.Format("/Content/ArticleMyndir/{0}.{1}", na.Title.Trim(), fileEnding[1]);
				}

                m_rep.UpdateNewsArticle( na );
				//1 is id on news

				return RedirectToAction( na.ContentType == 2 ? "MyNews" : "MyArticles" );
        	}
        	catch ( Exception ex )
        	{
				var log = new Logger( );
				log.LogExcepion( ex );
				return View( "Error" );
        	}
           
        }

        [HttpGet]
        public ActionResult CreateNews()
        {
            var model = new NewsArticle();
            model.ContentType = 2; //Id for news

            return View(model);
        }

        [HttpGet]
        public ActionResult CreateArticle()
        {
            NewsArticle model = new NewsArticle();
            model.ContentType = 1; //Id for article

            return View(model);
        }

        [ValidateInput(false)]
        [HttpPost]
        public ActionResult CreateArticle( NewsArticle na )
        {
        	try
        	{
				//validation
				if (String.IsNullOrEmpty( na.Title ) )
				{
					ModelState.AddModelError("Title", "Það verður að tilgreina titil greinar");
					return View( na );
				}

				if (String.IsNullOrEmpty( na.TextBody ) )
				{
					ModelState.AddModelError("Meginmál", "Það verður að tilgreina meginmál greinar");
					return View( na );
				}

				//check if file has been submited
/*				if (file != null && file.ContentLength > 0)
				{
					//file saved to hard drive and relative path from web aplication saved
					var fileEnding = file.FileName.Split('.');
					var folder = Path.Combine(Server.MapPath("~/Content/ArticleMyndir" ) );
					var path = Path.Combine(Server.MapPath("~/Content/ArticleMyndir"), na.Title.Trim() + "." + fileEnding[1]);

					//validate folder exist
					if (!Directory.Exists(folder))
					{
						Directory.CreateDirectory(folder);
					}

					file.SaveAs(path);
					na.Picture = string.Format("/Content/ArticleMyndir/{0}.{1}", na.Title.Trim(), fileEnding[1]);
				}*/

				na.Author = m_userMgr.CurrentUser;
				na.ContentDate = DateTime.Now;
				na.ContentType = 1;  //id for article
				m_rep.AddNewsArticle(na);
				return RedirectToAction("MyArticles");
        	}
        	catch ( Exception ex )
        	{
				var log = new Logger( );
				log.LogExcepion( ex );
				return View ("Error" );
        	}
        }


        [ValidateInput( false )]
        [HttpPost]
		public ActionResult CreateNews(NewsArticle na, HttpPostedFileBase file)
        {
        	try
        	{
				//validation
				if (String.IsNullOrEmpty( na.Title ) )
				{
					ModelState.AddModelError("Title", "Það verður að tilgreina titil fréttar");
					return View( na );
				}

				if ( String.IsNullOrEmpty( na.TextBody ) )
				{
					ModelState.AddModelError( "Meginmál", "Það verður að tilgreina meginmál fréttar" );
					return View( na );
				}

				//check if file has been submited
				if (file != null && file.ContentLength > 0)
				{
					//file saved to hard drive and relative path from web aplication saved
					var fileEnding = file.FileName.Split('.');
					var folder = Path.Combine(Server.MapPath("~/Content/ArticleMyndir"));
					var path = Path.Combine(Server.MapPath("~/Content/ArticleMyndir"), na.Title.Trim() + "." + fileEnding[1]);

					//validate folder exist
					if (!Directory.Exists(folder))
					{
						Directory.CreateDirectory(folder);
					}

					file.SaveAs(path);
					na.Picture = string.Format("/Content/ArticleMyndir/{0}.{1}", na.Title.Trim(), fileEnding[1]);
				}

				na.Author = m_userMgr.CurrentUser; 
				na.ContentDate = DateTime.Now;
				na.ContentType = 2;
				m_rep.AddNewsArticle( na );

				return RedirectToAction("MyNews");
        	}
        	catch ( Exception ex )
        	{
				var log = new Logger( );
				log.LogExcepion( ex );
				return View( "Error" );
        	}
        }


        public ActionResult MyNews( )
        {
        	try
        	{
				var strUser = User.Identity.Name;

				//news for currently logged in user fetched
				m_NewsArticle.NewsArticle = from ns in m_rep.GetAllNewsArticles()
											where ns.ContentType == 2
											where ns.Author == strUser
											select ns;

				m_NewsArticle.counter = m_NewsArticle.NewsArticle.Count();

				//nr of news per page set
				m_NewsArticle.displayNewsArticle = displayNewsArticles;

				//nr of pages calculated
				var n = m_NewsArticle.counter;
				m_NewsArticle.counter = n / displayNewsArticles;
				if ( n % displayNewsArticles != 0 )
				{
					m_NewsArticle.counter++;
				}
				return View(m_NewsArticle);
        	}
        	catch ( Exception ex )
        	{
				var log = new Logger( );
				log.LogExcepion( ex );
				return View( "Error" );
        	}
           
        }

        public ActionResult AllNews()
        {
            m_NewsArticle.NewsArticle = from ar in m_rep.GetAllNewsArticles()
                                        where ar.ContentType == 2
                                        select ar;
            m_NewsArticle.counter = m_NewsArticle.NewsArticle.Count();

			//nr of articles per page set
            m_NewsArticle.displayNewsArticle = displayNewsArticles;

			//nr of pages calculated
            var n = m_NewsArticle.counter;
            m_NewsArticle.counter = n / displayNewsArticles;
            
            if (n % displayNewsArticles != 0)
            {
                m_NewsArticle.counter++;
            }
            return View(m_NewsArticle);
        }

        public ActionResult MyArticles()
        {
        	try
        	{
				String strUser = User.Identity.Name;

				//news for currently logged in user fetched
				m_NewsArticle.NewsArticle = from ar in m_rep.GetAllNewsArticles()
											where ar.Author == strUser
											where ar.ContentType == 1
											select ar;

				m_NewsArticle.counter = m_NewsArticle.NewsArticle.Count();

				//nr of articles per page set
				m_NewsArticle.displayNewsArticle = displayNewsArticles;

				//nr of pages calculated
				var n = m_NewsArticle.counter;
				m_NewsArticle.counter = n / displayNewsArticles;

				if (n % displayNewsArticles != 0)
				{
					m_NewsArticle.counter++;
				}
				return View(m_NewsArticle);
        	}
        	catch ( Exception ex )
        	{
				var log = new Logger( );
				log.LogExcepion( ex );
				return View( "Error" );
        	}
            
        }


        public ActionResult AllArticles()
        {
            m_NewsArticle.NewsArticle = from ar in m_rep.GetAllNewsArticles()
                                        where ar.ContentType == 1
                                        select ar;

			//nr of article per page set
            m_NewsArticle.counter = m_NewsArticle.NewsArticle.Count();

			//nr of pages calculated
            m_NewsArticle.displayNewsArticle = displayNewsArticles;
            var n = m_NewsArticle.counter;
            m_NewsArticle.counter = n / displayNewsArticles;

            if (n % displayNewsArticles != 0)
            {
                m_NewsArticle.counter++;
            }

            return View(m_NewsArticle);
        }


        public static IQueryable<Category> GetAllCategories()
        {
            NewsArticleRepositry n_rep = new NewsArticleRepositry();

            var model = n_rep.GetAllCategories();

            return model;
        }


        [HttpGet]
        public ActionResult GetNewsArticleById( int? id )
        {
            //validation
            if ( ! id.HasValue )
            {
            	return View( "Error" );
            }

            var model = m_rep.GetNewsArticleById( id.Value );

            return View( model );
        }

        public ActionResult DisableNewsArticle( int? id )
        {
        	try
        	{
				//validation
				if (!id.HasValue)
				{
					return View( "Error" );
				}

				var newsArticle = m_rep.GetNewsArticleById(id.Value);
				if ( newsArticle != null )
				{
					String strUser = User.Identity.Name;
					var referrer = HttpContext.Request.UrlReferrer;
					m_rep.DisableNewsArticle(newsArticle, strUser);

					if ( referrer != null )
					{
						return Redirect(referrer.ToString());
					}
				}
				return View( );
        	}
        	catch ( Exception ex )
        	{
				var log = new Logger() ;
				log.LogExcepion( ex );
				return View ("Error" );
        	}
        }

        public ActionResult EnableNewsArticle( int? id )
        {
        	try
        	{
				//validation
				if (!id.HasValue)
				{
					return View("Error");
				}

				var newsArticle = m_rep.GetNewsArticleById(id.Value);

				if (newsArticle != null)
				{
					String strUser = User.Identity.Name;
					var referrer = HttpContext.Request.UrlReferrer;
					m_rep.EnableNewsArticle(newsArticle, strUser);

					if (referrer != null)
					{
						return Redirect(referrer.ToString());
					}
				}

				return View( );    
        	}
        	catch (Exception ex )
        	{
				var log = new Logger( );
				log.LogExcepion( ex );
				return View( "Error" );
        	}
        }


		public ActionResult GetEmailList()
		{
			EmailListRepository e_rep = new EmailListRepository( );

			m_NewsArticle.EmailList = e_rep.GetAllEmail( );
		
			return View( m_NewsArticle );
		}	 
    }
}
